package com.clw.template.admin.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.clw.template.dto.AdminLoginParam;
import com.clw.template.dto.SysAdminParam;
import com.clw.template.entity.SysAdmin;
import com.clw.template.service.ISysPermissionService;
import com.clw.template.service.ISysAdminService;
import com.clw.template.util.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author clw
 * @since 2019-11-01
 */
@Api(tags = "SysUserController",description = "后台用户表")
@RestController
@RequestMapping("/admin/admin")
public class SysAdminController {
    @Autowired
    private ISysAdminService sysUserService;
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private ISysPermissionService sysPermissionService;

    @ApiOperation("登录以后返回token")
    @PostMapping("login")
    public CommonResult login(@RequestBody AdminLoginParam adminLoginParam){
        String token = sysUserService.login(adminLoginParam.getUsername(),adminLoginParam.getPassword());
        if (token == null){
            return CommonResult.validateFailed("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @PreAuthorize("hasAuthority('sys:admin:info')")
    @ApiOperation("获取当前登录用户信息")
    @GetMapping("info")
    public CommonResult info(){
        SysAdmin admin = sysUserService.getLoginUserInfo();
        List<String> permissionList = sysPermissionService.getPermissionList(admin.getRoleId());
        Map<String,Object> data = new HashMap<>();
        data.put("username", admin.getUsername());
        data.put("roles", permissionList);
        data.put("icon", admin.getIcon());
        return CommonResult.success(data);
    }

    @PreAuthorize("hasAuthority('sys:admin:list')")
    @ApiOperation("查询用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize",value = "分页条数",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(name = "pageNum",value = "分页页数",dataType = "Integer",paramType = "query")
    })
    @GetMapping("list")
    public CommonResult<IPage<SysAdmin>> list(@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                              @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum){
        return CommonResult.success(sysUserService.userList(pageNum,pageSize));
    }

    @PreAuthorize("hasAuthority('sys:admin:getById')")
    @ApiOperation("获取指定用户")
    @GetMapping("{id}")
    public CommonResult<SysAdmin> getById(@PathVariable Long id){
        return CommonResult.success(sysUserService.getById(id));
    }

    @PreAuthorize("hasAuthority('sys:admin:add')")
    @ApiOperation("添加用户")
    @PostMapping("add")
    public CommonResult<SysAdmin> add(@Validated @RequestBody SysAdminParam userParam){
        if (StringUtils.isEmpty(userParam.getPassword())){
            return CommonResult.validateFailed("密码不能为空");
        }
        SysAdmin sysAdmin = new SysAdmin();
        BeanUtils.copyProperties(userParam, sysAdmin);
        sysAdmin.setCreateTime(LocalDateTime.now());
        sysAdmin.setUpdateTime(sysAdmin.getCreateTime());
        sysUserService.save(sysAdmin);
        return CommonResult.success();
    }

    @PreAuthorize("hasAuthority('sys:admin:deleted')")
    @ApiOperation("删除用户")
    @DeleteMapping("{id}")
    public CommonResult deleted(@PathVariable Long id){
        if (id == 1){
            return CommonResult.validateFailed("不能删除超级管理员");
        }
        sysUserService.deleted(id);
        return CommonResult.success();
    }

    @PreAuthorize("hasAuthority('sys:admin:edit')")
    @ApiOperation("修改用户")
    @PutMapping("{id}")
    public CommonResult edit(@PathVariable Long id,@Validated @RequestBody SysAdminParam userParam){
        SysAdmin sysAdmin = new SysAdmin();
        BeanUtils.copyProperties(userParam, sysAdmin);
        sysAdmin.setId(id);
        sysAdmin.setPassword(null); //密码单独修改
        sysAdmin.setUpdateTime(LocalDateTime.now());
        sysUserService.updateById(sysAdmin);
        return CommonResult.success();
    }

    @ApiOperation("修改指定用户密码")
    @PutMapping("updatePassword")
    @PreAuthorize("hasAuthority('sys:admin:updatePassword')")
    public CommonResult updatePassword(@RequestParam("id") String id, @RequestParam("resetPassword") String password){
        if (id == null || StringUtils.isEmpty(password)){
            return CommonResult.validateFailed("参数不能为空");
        }
        sysUserService.updatePassword(Long.valueOf(id),password);
        return CommonResult.success();
    }

    @ApiOperation("登出功能")
    @PostMapping("logout")
    @PreAuthorize("hasAuthority('sys:admin:logout')")
    public CommonResult logout(){
        return CommonResult.success();
    }

}
